<script lang="ts" setup>
import lodash from 'lodash'
import moment from 'moment'
import { computed } from 'vue'
import { ContactApi } from '~/api/ContactApi'
import { JobRecordApi } from '~/api/JobRecordApi'
import LxButton from '~/components/common/LxButton.vue'
import { ContactModel, JobRecordModel } from '~/model'
import { ScheduleModel } from '~/model/ScheduleModel'
import { NavBar } from 'vant';
import { SalaryModel } from '~/model/SalaryModel'

const router = useRouter()

const contacts = ref([] as ContactModel[])
const records = ref([] as JobRecordModel[])
const recordsLatest5 = computed(() => records.value.slice(0, 5))

const recordsGrouped = computed(() => lodash.groupBy(records.value, x => x.worker?.id))
const scheduleModels = computed(() => {
  return Object.values(recordsGrouped.value).map(arr => new ScheduleModel(arr))
})
const salaryModels = computed(() => {
  return Object.values(recordsGrouped.value).map(arr => new SalaryModel(arr))
})

const dayWorkers = computed(() => {
  return scheduleModels.value.filter(x => x.getSchedule() === '白班').map(x => x.worker())
})
const nightWorkers = computed(() => scheduleModels.value.filter(x => x.getSchedule() === '夜班').map(x => x.worker()))
const otherWorkers = computed(() => {
  const models = scheduleModels.value.filter((x) => {
    return !x.left() && x.getSchedule() !== '白班' && x.getSchedule() !== '夜班'
  })
  return models.map(x => x.worker())
})

// 离职工人
const leftWorkers = computed(() => scheduleModels.value.filter(x => x.left()).map(x => x.worker()))
// 未结清工人
const unsettledWorkers = computed(() => salaryModels.value.filter(x => x.unSettledRecords().length).map(x => x.worker()))
const leftUnsettledWorkers = computed(() => leftWorkers.value.filter(who => unsettledWorkers.value.findIndex(x => x.id === who.id) >= 0))
// const leftSettledWorkers = computed(() => leftWorkers.value.filter(who => unsettledWorkers.value.findIndex(x => x.id === who.id) < 0))


onMounted(() => {
  ContactApi.getAll()
    .then((res) => {
      contacts.value = res
    })
  JobRecordApi.getAll()
    .then((res) => {
      records.value = res
      records.value.sort((a, b) => b.id - a.id)
    })

  // 输出员工支取
  // setTimeout(() => {
  //   const filtered = records.value.filter(x => x.action === JobAction.Advance)
  //   const desp = filtered.map(x => `[${moment(x.date).format('YYYY-MM-DD')}] ${x.worker?.name}预支了${x.actionParams}`)
  //   console.log(desp.join('\n'))
  // }, 1000);
})
// const xxx = computed(() => {
//   const filtered = records.value.filter(x => x.action === JobAction.Advance)
//   // const desp = filtered.map(x => `[${moment(x.date).format('YYYY-MM-DD')}] ${x.worker?.name}预支了${x.actionParams}`)
//   return filtered
// })

function dateFormatter(r: JobRecordModel) {
  return moment(r.date).format('MM/DD')
}

function contentFormatter(r: JobRecordModel) {
  return `${r.worker!.name}${r.description()}`
}

function onBoard() {
  router.push('/jobs/events/detail?start=1')
}

function newEvent() {
  router.push('/jobs/events/detail?event=1')
}

function goDetail(row: JobRecordModel) {
  router.push(`/jobs/events/detail?id=${row.id}`)
}

function goSalarySheet() {
  router.push('/jobs/salary_sheet')
}

function goPauseBatch() {
  router.push('/jobs/events/pause_batch')
}

const unsettledStyle = computed(() => {
  return {
    color: leftUnsettledWorkers.value.length === 0 ? 'black' : 'white',
    backgroundColor: leftUnsettledWorkers.value.length === 0 ? 'white' : 'orange',
  }
})
</script>

<template>
  <div>
    <NavBar
      title="人事"
      left-text="返回"
      left-arrow
      @click-left="$router.replace('/')"
    />
    <div p4>
      <div mb2 h-20 flex>
        <div mb0 mr2 paper flex-grow-2 @click="$router.push(`/jobs/workers?mode=白班`)">
          <div flex items-center text-size-5 font-bold>
            <div>白班</div>
          <!-- <FontAwesomeIcon ml1 icon="angle-right" /> -->
          </div>
          <div>{{ dayWorkers.length }} 人</div>
        </div>
        <div mb0 mr2 paper flex-grow-2 bg-blue-9 c-white @click="$router.push(`/jobs/workers?mode=夜班`)">
          <div flex items-center text-size-5 font-bold>
            <div>夜班</div>
          <!-- <FontAwesomeIcon ml1 icon="angle-right" /> -->
          </div>
          <div>{{ nightWorkers.length }} 人</div>
        </div>
        <div mb0 paper flex-shrink-0 @click="$router.push(`/jobs/workers?mode=其他安排`)">
          <div flex items-center font-bold>
            <div>其他</div>
          <!-- <FontAwesomeIcon ml1 icon="angle-right" /> -->
          </div>
          <div>{{ otherWorkers.length }} 人</div>
        </div>
      </div>
      <div mb2 h-10 flex>
        <div mb0 mr2 paper flex flex-grow-2
          @click="$router.push(`/jobs/workers?mode=离职未结`)"
          :style="unsettledStyle">
          <div w-full text-center>
            <div v-if="leftUnsettledWorkers.length">{{ `离职未结 ${leftUnsettledWorkers.length} 人` }}</div>
            <div v-else>无离职未结人员</div>
          </div>
        </div>
        <div mb0 paper flex flex-grow-2 @click="$router.push(`/jobs/workers?mode=离职结清`)">
          <div w-full text-center>查看离职结清人员</div>
        </div>
      </div>
      <div h-20 flex mt>
        <div position-relative mr2 paper flex-grow-1 bg-amber c-white @click="goSalarySheet">
          <div flex items-center text-size-5 font-bold>
            <div>工资表</div>
          </div>
        </div>
        <div position-relative mr2 paper flex-grow-1 bg-emerald c-white @click="onBoard">
          <div flex items-center text-size-5 font-bold>
            <div>入职</div>
          </div>
        </div>
        <div paper flex-grow-1 bg-sky-5 c-white @click="newEvent">
          <div flex items-center text-size-5 font-bold>
            <div>新事务</div>
          </div>
        </div>
      </div>
      <div flex>
        <div position-relative paper flex-grow-1 bg-purple c-white @click="goPauseBatch">
          <div flex items-center text-size-5 font-bold>
            <div>批量请假</div>
          </div>
        </div>
      </div>
      <div mb paper of-hidden p0>
        <table class="lx-table">
          <thead>
            <tr>
              <td>日期</td>
              <td>
                事务
              </td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in recordsLatest5" :key="index" @click="goDetail(item)">
              <td>
                {{ dateFormatter(item) }}
              </td>
              <td>
                {{ contentFormatter(item) }}
              </td>
            </tr>
          </tbody>
        </table>
        <LxButton title="查看全部" w-full b-rd-0 :action="() => $router.push('/jobs/events')" />
      <!-- <table>
        <tbody>
          <tr v-for="(item, index) in xxx" :key="index">
            <td>{{ moment(item.date).format('YYYY-MM-DD') }}</td>
            <td>{{ item.worker?.name }}</td>
            <td>{{ item.actionParams[0] }}</td>
            <td>{{ item.actionParams[1] }}</td>
          </tr>
        </tbody>
      </table> -->
      </div>
    </div>
  </div>
</template>

<style scoped>
.card-sun {
  background-image: url('/icons/sun.png');
  background-repeat: no-repeat;
  background-position: 90% 90%;
}

.card-moon {
  background-image: url('/icons/moon.png');
  background-repeat: no-repeat;
  background-position: 90% 90%;
}
</style>

<route lang="yaml">
meta:
  title: 人事
</route>
